package com.azt.back.freemarker;

import com.azt.api.pojo.LevelConfig;
import com.azt.api.pojo.LevelUser;
import com.azt.api.service.LevelConfigService;
import com.azt.api.service.LevelUserService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

/**
 * 等级查询
 * [@u_level companyId=integer]
 * @see com.azt.enums.LevelTypeEnum
 * Created by LiQZ on 2017/4/18.
 */
@Component("u_level")
public class LevelDirective implements TemplateDirectiveModel {

    @Autowired
    private LevelUserService levelUserService;

    @Autowired
    private LevelConfigService levelConfigService;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            execute0(env, params, body);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void execute0(Environment env, Map params, TemplateDirectiveBody body) throws TemplateException, IOException {
        Integer companyId = DirectiveUtils.getInt("companyId", params);
        // 查询出所用的值
        LevelUser user = levelUserService.get(companyId);
        // 查询该值所属等级
        Map<String, LevelConfig> configs = levelConfigService.find(user);
        // 该map 用来临时保存 参数
        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);

        // configMap.put("purchase", purchaseConfig);
        // configMap.put("provider", providerConfig);
        for (Map.Entry<String, LevelConfig> entry: configs.entrySet()) {
            paramWrap.put(entry.getKey(), DEFAULT_WRAPPER.wrap(entry.getValue()));
        }

        Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);

        body.render(env.getOut());

        DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
    }

}
